<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>

    <div th:replace="fragments/header :: header-meta"/>

    <div th:replace="fragments/header :: header-css"/>

    <title>文章 - <span th:utext="#{title}" th:remove="tag"></span> · <span th:utext="#{slogan}" th:remove="tag"></span></title>

    <style type="text/css">
        #left-categories {
            cursor: pointer;
            font-size: 15px;
            font-weight: 300;
            list-style: none;
            width: 100%;
            margin-left: -25px;
            margin-top: 20px;
        }
        .left-category {
            margin-bottom: 20px;
            border-radius: 5px;
            font-weight: lighter;
            margin-left: 15px;
            cursor: pointer;
        }
        .left-category:hover {
            background-color: #8c939d;
        }
    </style>

</head>
<body>

    <div id="app">

        <div id="header">
            <div th:replace="fragments/header :: header-light"/>
        </div>

        <main class="container" style="margin-top: 100px; margin-bottom: 100px; min-height: 1000px;">

            <div class="row">
                <div class="col-md-5">
                    <el-breadcrumb separator-class="el-icon-arrow-right" style="padding-top: 13px">
                        <el-breadcrumb-item>
                            <a :href="formatSupportUrl()" target="_blank">帮助中心</a>
                        </el-breadcrumb-item>
                        <el-breadcrumb-item style="cursor: pointer;" v-for="category in categories" :key="category.id">
                            <a :href="formatCategoryUrl(category.cid)" target="_blank">{{ category.name }}</a>
                        </el-breadcrumb-item>
                    </el-breadcrumb>
                </div>
                <div class="col-md-4"></div>
                <div class="col-md-3">
                    <el-input placeholder="请输入内容" v-model="searchContent" clearable>
                        <el-button slot="append" icon="el-icon-search" @click="handleSearch()"></el-button>
                    </el-input>
                </div>
            </div>

            <div class="row" style="margin-top: 60px;">

                <div class="col-md-3 d-none d-md-block">

                    <p>此类别内的其他文章</p>

                    <!--style="font-weight: lighter; margin-left: 15px; margin-top: 10px; cursor: pointer;"-->
                    <div class="left-categories">
                        <div class="left-category" v-for="article in related" @click="getArticle(article.aid)">{{ article.title }}</div>
                    </div>

                </div>

                <div class="col-md-9">
                    <div class="row">
                        <h3>{{ article.title }}</h3>
                    </div>
                    <div class="row" style="margin-top: 20px; margin-bottom: 40px;">
                        <div class="col-md-1">
                            <img :src="article.user.avatar" width="40px" height="40px">
                        </div>
                        <div class="col-md-9">
                            <div class="row" style="font-size: 15px;">{{ article.user.name }}</div>
                            <div class="row" style="font-size: 14px; color: gray; font-weight: lighter;">{{ formatDate(article.createdAt) }}</div>
                        </div>
                        <div class="col-md-2">
                            <div class="row" style="font-size: 10px; color: gray; float: right;">
                                阅读次数:{{ article.readCount }}
                            </div>
                        </div>
                    </div>
                    <hr>
                    <div class="row" style="font-weight: 300; ">
                        <span v-if="article.markdown" v-html="compiledMarkdown"></span>
                        <span v-if="!article.markdown" v-html="article.content"></span>
                    </div>
                    <!--<div class="row">分享</div>-->
                    <hr>
                    <div class="row" style="font-weight: 300; font-size: 14px;">
                        <div class="col-md-4"></div>
                        <div class="col-md-4">
                            <div class="row">
                                <span style="width: 100%; text-align: center;">
                                    这篇文章有帮助吗？
                                </span>
                            </div>
                            <div class="row" style="margin-top: 10px; width: 100%; margin-left: 25px;">
                                <el-button size="mini" @click="rateArticle(true)"><i class="iconfont icon-agree"></i> 有帮助</el-button>
                                <el-button size="mini" @click="rateArticle(false)"><i class="iconfont icon-disagree"></i> 无帮助</el-button>
                            </div>
                            <div class="row">
                                <span style="width: 100%; text-align: center; margin-top: 10px;">
                                    {{ rateTotal }} 人中有 {{ article.rateHelpful }} 人觉得有帮助
                                </span>
                            </div>
                        </div>
                        <div class="col-md-4"></div>
                    </div>
                    <hr>
                    <div class="row">
                        <div class="col-md-6">最近查看的文章</div>

                        <!--TODO: 同一个用户一天之内阅读超过5篇文档，则增加5个积分，并右上角pop提示-->

                        <!--TODO: 增加 前一篇、后一篇 文章链接-->

                        <!--TODO: 一期根据文章类别显示，二期根据用户画像推荐-->
                        <div class="col-md-6">相关文章</div>
                    </div>
                    <hr>
                    <div style="padding-left: 15px;">
                        <!--TODO: 二期增加评论功能，后台可开关，或者利用第三方评论系统畅言-->
                        <div class="row">评论</div>
                        <div class="row" style="font-size: 10px;font-weight: lighter;">0条评论</div>
                    </div>
                    <hr>

                </div>

            </div>

        </main>

    </div>

    <div th:replace="fragments/footer :: footer-div"/>

    <div th:replace="fragments/footer :: footer-js"/>

    <div th:replace="fragments/footer :: footer-chat"/>

    <script src="https://cdn.bootcss.com/marked/0.5.1/marked.min.js"></script>
    <script type="text/javascript">
        // axios.defaults.baseURL =  "/visitor/api/";
        var app = new Vue({
            el: "#app",
            data() {
                return {
                    uid: "",
                    aid: "",
                    /**
                     *
                     */
                    username: '',
                    password: '',
                    // 本地存储access_token的key
                    token: 'token',
                    passport: {
                        token: {
                            access_token: '',
                            expires_in: 0,
                            jti: '',
                            refresh_token: '',
                            scope: '',
                            token_type: ''
                        }
                    },
                    userId: '',
                    subDomain: '',
                    client: 'web',
                    /**
                     *
                     */
                    categories: [],
                    related: [],
                    article: {
                        title: "",
                        content: "",
                        createdAt: "",
                        user: {
                            name: "",
                            avatar: ""
                        }
                    },
                    searchContent: ""
                }
            },
            computed: {
                rateTotal() {
                    return this.article.rateHelpful + this.article.rateUseless;
                },
                compiledMarkdown: function () {
                    return marked(this.article.content, { sanitize: true })
                }
            },
            methods: {
                getUrlParam(name) {
                    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
                    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
                    if (r != null) return decodeURIComponent(r[2]);
                    return null; //返回参数值
                },
                handleSearch() {
                    window.open("/support/search?uid=" + this.uid + "&content=" + this.searchContent);
                },
                formatDate(date) {
                    return moment(date).format('MM-DD HH:mm')
                },
                formatSupportUrl() {
                    return "/support?uid=" + this.uid;
                },
                formatArticleUrl(aid) {
                    return "/support/article?uid="+this.uid+"&aid=" + aid;
                },
                formatCategoryUrl(cid) {
                    return "/support/category?uid="+this.uid+"&cid=" + cid
                },
                /**
                 * 工具函数
                 */
                initAxios() {
                    // http response 拦截器
                    axios.interceptors.response.use(
                        response => {
                            return response
                        },
                        error => {
                            if (error.response) {
                                switch (error.response.status) {
                                    case 401:
                                        console.log('axios interception error 401');
                                    case 403:
                                        // 401 清除token信息并登录
                                        // 403 无权限，跳转到首页
                                        console.log('axios interception error 403');
                                        localStorage.removeItem(app.token);
                                        if (app.username !== undefined
                                            && app.username !== null
                                            && app.username !== '') {
                                            app.login()
                                        } else {
                                            app.requestUsername();
                                        }
                                }
                            }
                            return 'return axios interception error'
                        })
                },
                /**
                 * 1. 首先判断是否已经注册过
                 * 2. 如果已经注册过，则直接调用登录接口
                 * 3. 如果没有注册过，则从服务器请求用户名
                 *
                 * FIXME: 暂未考虑浏览器不支持localStorage的情况
                 */
                requestUsername () {
                    this.username = localStorage.username;
                    if (this.username) {
                        this.password = this.username;
                        this.login();
                    } else {
                        //
                        axios.get('/visitor/api/username', {
                            params: {
                                'subDomain': this.subDomain,
                                'client': this.client
                            }
                        }).then(response => {
                            console.log('username:', response.data);
                            // 登录
                            app.username = response.data.data;
                            app.password = app.username;
                            // 本地存储
                            localStorage.username = app.username;
                            // 登录
                            app.login();
                        }).catch(error => {
                            console.log(error)
                        });
                    }
                },
                /**
                 * 2. oauth2登录
                 */
                login () {
                    axios({
                        method: 'post',
                        url: '/oauth/token',
                        params: {
                            'username': this.username,
                            'password': this.password,
                            'grant_type': 'password',
                            'scope': 'all'
                        },
                        auth: {
                            username: 'client',
                            password: 'secret'
                        }
                    }).then(function (response) {
                        console.log('login success: ',response.data);
                        // 本地存储，
                        app.passport.token = response.data;
                        // localStorage 存储
                        localStorage.setItem(app.token, JSON.stringify(response.data));
                        // 请求文章内容
                        app.getArticle(app.aid)
                    }).catch(function (error) {
                        console.log(error)
                    })
                },
                getArticle(aid) {
                    this.aid = aid;
                    // TODO: 添加access_token
                    axios.get('/api/article/detail?access_token=' + this.passport.token.access_token, {
                        params:{
                            'uid': this.userId,
                            'aid': this.aid,
                        }
                    })
                    .then(function (response) {
                        console.log("fetch article success:",response.data);
                        if (response.data.status_code === 200)  {
                            app.article = response.data.data.article;
                            app.related = response.data.data.related;
                            app.categories = app.article.categories;
                        } else {
                            this.$message.warning(response.data.message)
                        }
                    })
                    .catch(function (error) {
                        console.log("fetch article error:",error);
                    });
                },
                rateArticle(rate) {
                    // TODO: 添加access_token
                    axios.post('/api/article/rate?access_token=' + this.passport.token.access_token, {
                        uid: this.userId,
                        aid: this.aid,
                        rate: rate,
                        client: 'web'
                    }).then(response => {
                        console.log("success:", response.data);
                        if (response.data.status_code === 200)  {
                            app.article = response.data.data
                        } else {
                            this.$message.warning(response.data.message)
                        }
                    }).catch(error => {
                        console.log(error);
                    });
                }
            },
            created() {
                // console.log(('created'));
                this.uid = this.getUrlParam("uid");
                this.aid = this.getUrlParam("aid");
                //
                this.username = localStorage.username;
                this.password = this.username;
                var tokenLocal = localStorage.getItem(this.token);
                if (tokenLocal != 'undefined') {
                    this.passport.token = JSON.parse(tokenLocal);
                }
            },
            mounted() {
                // console.log(('mounted'));
                this.initAxios();

                if (this.username !== null
                    && this.username !== undefined
                    && this.username !== '') {
                    this.login()
                } else {
                    this.requestUsername();
                }
            }
        })
    </script>

</body>
</html>
